package pers.jphoebe.quartz.handler;

import org.springframework.stereotype.Component;
import pers.jphoebe.quartz.api.juhe.JuheApi;
import pers.jphoebe.quartz.api.juhe.impl.GoldApiImpl;
import pers.jphoebe.quartz.entity.response.ErrorCode;
import pers.jphoebe.quartz.entity.response.ResponseData;
import pers.jphoebe.quartz.utils.Logger;
import pers.jphoebe.quartz.utils.StackTraceUtils;

import java.util.concurrent.TimeUnit;

/**
 * Created by 蒋时华 on 2017/10/31.
 */
public class JuheResponseHandler<T> {

    private final Logger logger = Logger.getLogger(this.getClass());

    public T handle(JuheApi<T> juheApi) {
        T result = null;
        logger.info(null,"请求返回值处理");
        try {
            result = juheApi.invokeJuheAPI();
            ResponseData responseData = (ResponseData) result;
            if(!ErrorCode.SUCCESS_CODE.getCode().equals(responseData.getCode())){
                this.retry(juheApi);
            }
        }catch (Exception e){
            logger.error(StackTraceUtils.getStackTraceStr(e));
        }
        return result;
    }

    /**
     * 三次重新请求重试
     * @param goldApi
     * @return
     */
    public T retry(JuheApi<T> juheApi) {
        T result = null;
        long time = 5;
        for (int i = 0; i < 3; i++) {
            try {
                TimeUnit.SECONDS.sleep(time);
                logger.info(null,"Reconnection is in progress...");
                result = juheApi.invokeJuheAPI();
                if (result != null) {
                    return result;
                }
            } catch (Exception e1) {
                time *= 3;
            }
        }
        return result;
    }

}
